package com.ruoyi.framework.config;

import com.ruoyi.framework.interceptor.RequestNonceInterceptor;
import com.ruoyi.framework.interceptor.RequestPrintInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.CacheControl;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.framework.interceptor.RepeatSubmitInterceptor;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

import java.util.concurrent.TimeUnit;

/**
 * 通用配置
 *
 * @author ruoyi
 */
@Configuration
public class ResourcesConfig implements WebMvcConfigurer {
    @Autowired
    private RepeatSubmitInterceptor repeatSubmitInterceptor;

    @Autowired
    private RequestPrintInterceptor requestPrintInterceptor;

    @Autowired
    private RequestNonceInterceptor requestNonceInterceptor;

    @Value("${ruoyi.requestPrintEnable}")
    private boolean requestPrintEnable;

    @Value("${ruoyi.nonceEnable}")
    private boolean nonceEnable;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        /** 本地文件上传路径 */
        registry.addResourceHandler(Constants.RESOURCE_PREFIX + "/**")
                .addResourceLocations("file:" + RuoYiConfig.getProfile() + "/");

        /** swagger配置 */
        registry.addResourceHandler("/swagger-ui/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/")
                .setCacheControl(CacheControl.maxAge(5, TimeUnit.HOURS).cachePublic());
    }

    /**
     * 自定义拦截规则
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(repeatSubmitInterceptor).addPathPatterns("/**");

        //请求拦截打印
        if (requestPrintEnable) {
            registry.addInterceptor(requestPrintInterceptor).addPathPatterns("/**");
        }

        //nonce校验
        if (nonceEnable) {
            registry.addInterceptor(requestNonceInterceptor).addPathPatterns("/**")
                    .excludePathPatterns(
                            "/common/**",
                            "/**/importData",
                            "/system/attachment/uploadAttachment",
                            "/system/area/**",
                            "/system/dept/**"
                    );
        }

    }

    /**
     * 开启websocket
     */
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}